#include <iostream>
#include <cstring>
#include <cctype>
#include <queue>
using namespace std;
int W, H, N;
constexpr int MAXN = 1001;
char map[MAXN][MAXN];
char mapcopy[MAXN][MAXN];
int sx, sy;
void solve();

struct Rat{
    pair<int, int> pos;
    int pace;
    Rat(int _x, int _y, int _pace): pos(_x, _y), pace(_pace) {}
    Rat(pair<int, int> _pos, int _pace): pos(_pos), pace(_pace) { }
};
pair<int, int> milk[11];

int main() {
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++) 
        for (int j = 0; j < W; j++) {
            cin >> map[i][j];
            if (map[i][j] == 'S') {
                sx = i; sy = j;
                milk[0] = make_pair(sx, sy);
            }
            if (isdigit(map[i][j])) {
                milk[map[i][j] - '0'] = make_pair(i, j);
            } 
        }
    solve();
}

int dxdy[][4] = {
    {0, 0, 1, -1},
    {1, -1, 0, 0}
};

bool check(int x, int y) {
    return x >=0 && x < H && y >= 0 && y < W && mapcopy[x][y] != 'X';
}

int bfs(pair<int, int> s, pair<int, int> e) {
    memcpy(mapcopy, map, sizeof mapcopy);
    queue<Rat> q;
    q.emplace(s, 0);
    mapcopy[s.first][s.second] = 'X';
    while (!q.empty()) {
        Rat t = q.front(); q.pop();
        if (t.pos == e) {
            return t.pace;
        }
        for (int i = 0; i < 4; i++) {
            int nx = t.pos.first + dxdy[0][i];
            int ny = t.pos.second + dxdy[1][i];
            if (check(nx, ny)) {
                q.emplace(nx, ny, t.pace + 1);
                mapcopy[nx][ny] = 'X';
            }
        }
    }
    return 0;
}
void solve() {
    int sum = 0;
    for (int i = 0; i < N; i++) {
        sum += bfs(milk[i], milk[i + 1]);
    }
    cout << sum << endl;
}